from google.appengine.api import users
from google.appengine.ext import db

from Achado import Achado
from Conta import Conta

class Manager:
	def meusAchados( self ):
		user = users.get_current_user()
		if user:
			achados = Achado.gql( "WHERE author = :1", user )
			return achados

	def adicionarAchado( self, achado ):
		if users.get_current_user():
			achado.author = users.get_current_user()
			achado.put()

	def listarUltimosAchados( self ):
		achados = Achado.gql( 'ORDER BY cadastro DESC, nome DESC LIMIT 10' )
		return achados

	def apagarAchado( self, key ):
		if users.get_current_user():
			oferta = db.get( key )
			db.delete( oferta )

	def getAchado( self, key ):
		if users.get_current_user():
			return db.get( key )

	def achei(self, key):
		achado = db.get( key )
		user = users.get_current_user()
		if user:
			achado.quem_achou = user
			achado.put()

	def buscarAchados( self, nome ):
		return Achado.all().search( nome )

	def getConta( self, user=None ):
		user = user or users.get_current_user()
		if user:
			conta = Conta.gql( "WHERE user = :1", user ).get()
			
			if not conta:
				conta = Conta()
				conta.user = user
				
			return conta
			
	def atualizarConta( self, conta ):
		if users.get_current_user():
			conta.put()
